package com.ruoyi.framework.config;

import cn.xbatis.core.XbatisGlobalConfig;
import cn.xbatis.core.incrementer.IdWorkerGenerator;
import cn.xbatis.core.incrementer.IdentifierGeneratorFactory;
import cn.xbatis.core.mybatis.configuration.MybatisConfiguration;
import com.ruoyi.framework.dataPermission.MybatisDataPermissionInterceptor;
import com.ruoyi.framework.dataPermission.XbatisDataPermissionMethodInterceptor;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.ruoyi.common.helper.LoginHelper.*;

@Configuration
public class XbatisConfig {

    @Bean
    ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(MybatisConfiguration configuration) {
                configuration.addInterceptor(new MybatisDataPermissionInterceptor());
                XbatisGlobalConfig.addMapperMethodInterceptor(new XbatisDataPermissionMethodInterceptor());
                IdentifierGeneratorFactory.register("IDS", new IdWorkerGenerator());
                XbatisGlobalConfig.setDynamicValue("{NAME}", (entity, type) -> {
                    return getUsername();
                });

                XbatisGlobalConfig.setDynamicValue("{USERID}", (entity, type) -> {
                    return getUserId();
                });
                XbatisGlobalConfig.setDynamicValue("{DeptID}", (entity, type) -> {
                    return getDeptId();
                });
            }
        };
    }
}
